package cn.edu.cque.mall.filter;

import cn.edu.cque.mall.entity.InfoResult;
import cn.edu.cque.mall.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName LoginInterceptor
 * @Description
 * @Author chen
 * @Date 2020/10/12 0012 11:01
 */
@Controller
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isAjax = false;
        String ajaxHeader = request.getHeader("X-Requested-With");
        if ((!StringUtils.isEmpty(ajaxHeader)) && ajaxHeader.equalsIgnoreCase("XMLHttpRequest")) {
            isAjax = true;
        }
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            // 未登录
            if (isAjax) {
                ObjectMapper objectMapper = new ObjectMapper();
                response.setContentType("application/json;charset=utf-8");
                objectMapper.writeValue(response.getWriter(), InfoResult.ERROR("用户未登录"));
            } else {
                response.sendRedirect(request.getContextPath() + "/jsp/login.jsp");
            }
        } else {
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
